package org.edu.service;

import java.util.List;
import java.util.Set;

import org.edu.dao.PurviewTreeNodeDao;
import org.edu.dao.RoleDao;
import org.edu.dao.UserDao;
import org.edu.model.Purview;
import org.edu.model.Role;
import org.edu.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = { RuntimeException.class }, propagation = Propagation.REQUIRED)
public class PurviewTreeNodeService extends ServiceAdapter<Purview, Integer>{
	
	//private static final Logger logger = Logger.getLogger(PurviewTreeNodeService.class);
	@Autowired
	private PurviewTreeNodeDao purviewTreeNodeDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserDao userDao;
	@Override
	public List<Purview> list() {
		// TODO Auto-generated method stub
		return purviewTreeNodeDao.loadAll();
	}
	
	public List<Purview> list(String id) {
		// TODO Auto-generated method stub
		return purviewTreeNodeDao.loadAll();
	}
	
	@Override
	public Purview show(Integer id) {
		// TODO Auto-generated method stub
		return purviewTreeNodeDao.get(id);
	}

	/**
	 * 获取角色下的所有权限，并且将已有的权限默认打勾
	 * @param role  需要获取的角色id
	 * @return
	 */
	public List<Purview> loadlist(String role) {
		Role r=roleDao.get(role);
		
		Set<Purview> sp=r.getPurview();
		List<Purview> lp= purviewTreeNodeDao.loadAll();

		for(Purview p:sp){
			for(int j=0;j<lp.size();j++){
				if(p.equals(lp.get(j))){
					lp.get(j).setChecked(true);
					break;
				}
			}
		}
		return lp;
	}
	/**
	 * 获取用户的所有权限
	 * @param user
	 * @return
	 */
	public List<Purview> loaduserpurview(String user){
		User u=userDao.get(user);
		Role r= u.getRoleid();
		Set<Role> sr= u.getSroleid();

		
		Set<Purview> sp=r.getPurview(); //主角色权限
		for(Role rit:sr){//辅助角色权限
			sp.addAll(rit.getPurview());
		}

		List<Purview> lp= purviewTreeNodeDao.loadAll();
		for(Purview p:sp){
			for(int j=0;j<lp.size();j++){
				if(p.equals(lp.get(j))){
					lp.get(j).setChecked(true);
					break;
				}
			}
		}
		return lp;
	}
	
	
}
